import { isString } from '/@/utils/is'
import { getCurrentInstance } from 'vue'
import { useGlobSetting } from '@/hooks/setting'
import { RoleEnum } from '@/enums/roleEnum'
import { useUserStoreWithOut } from '/@/store/modules/user'
const globSetting = useGlobSetting()
const { urlPrefix } = globSetting
const { getRoles } = useUserStoreWithOut()
/**
 * 权限访问模块封装
 * @returns
 */
export function usePermission() {
  const vm = getCurrentInstance()
  if (!vm) throw new Error('must be called in setup')
  /**
   * 是有有权限
   * @param code 逗号拼接的字符串
   * @returns
   */
  const hasPermission = (code?: string[] | string | RoleEnum[]): boolean => {
    if (!code) {
      new Error('v-action缺少唯一指令')
      return false
    }

    const actions = ((isString(code) ? (code as string).split(',') : code) as any).map((v) => `${urlPrefix}.${v}`) // action权限名称
    const { isSuper, permissions } = getRoles // 当前角色配置
    // 如果是超级管理员或是 codes:[*] 表示不验证权限
    if (isSuper || permissions?.includes('*')) return true
    // 如果权限存在，不做任何操作
    if (permissions.filter((p) => actions.includes(p))?.length) return true
    return false
  }
  /**
   * 是有有权限
   * @param code  逗号拼接的字符串
   * @returns
   */
  const hasPermissions = (parentCode: string, actions: string[]): boolean => {
    if (!actions.length) {
      new Error('缺少唯一指令')
      return false
    }
    // console.log(urlPrefix,parentCode,actions)
    const { isSuper, permissions } = getRoles // 当前角色配置
    // 如果是超级管理员或是 codes:[*] 表示不验证权限
    if (isSuper || permissions?.includes('*')) return true
    // 如果权限存在，不做任何操作
    if (permissions.filter((p) => actions.map((v) => `${urlPrefix}.${parentCode}.${v}`).includes(p))?.length)
      return true
    return false
  }
  /**
   * 是否展示
   * @param column table配置的字段
   * @returns
   */
  const filterAction = (column: any) => column.scopedSlots?.customRender !== 'action' && column?.dataIndex !== 'action'
  return {
    hasPermission,
    hasPermissions,
    filterAction,
  }
}
